import axios from 'axios'
import { auth } from './auth'

// 创建axios实例
const request = axios.create({
    baseURL: 'http://localhost:8080/api',
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器 - 添加token
request.interceptors.request.use(
    config => {
        const token = auth.getToken()
        console.log('请求拦截器 - 获取到的Token:', token ? `${token.substring(0, 20)}...` : 'null')
        
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
            console.log('请求拦截器 - 已设置Authorization头:', config.headers.Authorization.substring(0, 30) + '...')
        } else {
            console.warn('请求拦截器 - 未找到Token，将发送无认证请求')
        }
        
        console.log(`发送请求: ${config.method?.toUpperCase()} ${config.url}`)
        console.log('请求头信息:', {
            'Content-Type': config.headers['Content-Type'],
            'Authorization': config.headers.Authorization ? 'Bearer ***' : '未设置'
        })
        console.log('完整请求配置:', {
            method: config.method,
            url: config.url,
            baseURL: config.baseURL,
            headers: config.headers,
            data: config.data,
            params: config.params
        })
        
        return config
    },
    error => {
        console.error('请求拦截器错误:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器 - 处理认证和错误
request.interceptors.response.use(
    response => {
        console.log(`响应成功: ${response.config.method?.toUpperCase()} ${response.config.url}`, {
            status: response.status,
            data: response.data
        })
        return response.data
    },
    error => {
        console.error('API请求错误:', {
            url: error.config?.url,
            method: error.config?.method,
            status: error.response?.status,
            statusText: error.response?.statusText,
            data: error.response?.data,
            message: error.message
        })
        
        // 检查是否是401错误（JWT过期或无效）
        const is401Error = error.response?.status === 401 || error.response?.data?.code === 401
        
        if (is401Error) {
            console.log('检测到401错误，开始处理认证失效逻辑')
            
            // 清除认证信息
            auth.clearAuth()
            console.log('已清除本地存储的认证信息')
            
            // 检查当前路径，避免在登录页面重复跳转
            const currentHash = window.location.hash
            const isLoginPage = currentHash.includes('/login')
            
            if (!isLoginPage) {
                console.log('当前不在登录页，准备跳转到登录页')
                // 保存当前页面路径用于登录后跳转
                const currentPath = currentHash.replace('#', '') || '/dashboard'
                const loginUrl = `/#/login?redirect=${encodeURIComponent(currentPath)}`
                
                console.log('跳转到登录页:', loginUrl)
                
                // 使用setTimeout确保当前请求处理完成后再跳转
                setTimeout(() => {
                    window.location.href = loginUrl
                }, 100)
            } else {
                console.log('当前已在登录页，不需要跳转')
            }
            
            // 返回统一的401错误
            return Promise.reject({
                code: 401,
                message: 'Token已过期或无效，请重新登录',
                isAuthError: true
            })
        }
        
        // 处理其他HTTP错误
        const errorMessage = error.response?.data?.message || 
                           error.response?.statusText || 
                           error.message || 
                           '网络请求失败'
        
        const errorCode = error.response?.status || 500
        
        console.log(`处理非401错误 - 状态码: ${errorCode}, 错误信息: ${errorMessage}`)
        
        return Promise.reject({
            code: errorCode,
            message: errorMessage,
            data: error.response?.data || null,
            originalError: error
        })
    }
)

export default request 